<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT">










<meta name="description" content="详解C/C++的内存布局，以及C++对象内存布局，以及C和C++内存布局之间有什么区别。">
<meta property="og:type" content="article">
<meta property="og:title" content="C&#x2F;C++内存布局策略详解">
<meta property="og:url" content="http://luqilinok.github.io/2019/07/07/cpluscplusmemory/index.html">
<meta property="og:site_name" content="Lu QiLin&#39;s Blog">
<meta property="og:description" content="详解C/C++的内存布局，以及C++对象内存布局，以及C和C++内存布局之间有什么区别。">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://luqilinok.github.io/2019/07/07/cpluscplusmemory/c-memory.png">
<meta property="og:updated_time" content="2019-07-07T07:20:47.027Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="C&#x2F;C++内存布局策略详解">
<meta name="twitter:description" content="详解C/C++的内存布局，以及C++对象内存布局，以及C和C++内存布局之间有什么区别。">
<meta name="twitter:image" content="http://luqilinok.github.io/2019/07/07/cpluscplusmemory/c-memory.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://luqilinok.github.io/2019/07/07/cpluscplusmemory/">





  <title>C/C++内存布局策略详解 | Lu QiLin's Blog</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Lu QiLin's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-technology">
          <a href="/categories/Technology/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            Technology
          </a>
        </li>
      
        
        <li class="menu-item menu-item-notes">
          <a href="/categories/Notes/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            Notes
          </a>
        </li>
      
        
        <li class="menu-item menu-item-personal">
          <a href="/categories/Personal/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            Personal
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            About
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://luqilinok.github.io/2019/07/07/cpluscplusmemory/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="LuQiLin">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Lu QiLin's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">C/C++内存布局策略详解</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2019-07-07T14:58:55+08:00">
                2019-07-07
              </time>
            

            

            
          </span>
          
  <span class="post-updated">
    &nbsp; | &nbsp; 更新于
    <time itemprop="dateUpdated" datetime="2019-07-07T15:20:47+08:00" content="2019-07-07">
      2019-07-07
    </time>
  </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">In</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Notes/" itemprop="url" rel="index">
                    <span itemprop="name">Notes</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>详解C/C++的内存布局，以及C++对象内存布局，以及C和C++内存布局之间有什么区别。</p>
<a id="more"></a>
<hr>
<h1 id="C程序内存布局"><a href="#C程序内存布局" class="headerlink" title="C程序内存布局"></a>C程序内存布局</h1><p><img src="/2019/07/07/cpluscplusmemory/c-memory.png" alt></p>
<p>主要分为以下几部分组成：</p>
<p>​    · 代码段</p>
<p>​    · 初始化数据段（数据段）</p>
<p>​    · 未初始化数据段</p>
<p>​    · 堆</p>
<p>​    · 栈</p>
<p>下面分别来介绍各部分的作用：</p>
<hr>
<h2 id="代码段"><a href="#代码段" class="headerlink" title="代码段"></a>代码段</h2><p>代码段是由程序中的机器代码组成的，在C语言中，程序经过编译后，形成机器代码。在执行的过程中，CPU的程序计数器指向代码段中的一条指令，依次执行。</p>
<hr>
<h2 id="初始化数据段"><a href="#初始化数据段" class="headerlink" title="初始化数据段"></a>初始化数据段</h2><p>初始化数据段中数据又可以分为<strong>只读数据段</strong>和<strong>读写数据段</strong>：</p>
<p>（1）只读数据段是程序使用的一些不会被更改的数据，比如字面值常量，由于这些变量不需要修改，因此只需放置在只读寄存器中即可。</p>
<p>（2）读写数据段放置的是在程序中声明的，具有初始值的变量，比如已初始化的全局变量和静态变量。</p>
<hr>
<h2 id="未初始化数据段（BSS段）"><a href="#未初始化数据段（BSS段）" class="headerlink" title="未初始化数据段（BSS段）"></a>未初始化数据段（BSS段）</h2><p>未初始化数据段也称为BSS段，即Block Started by Symbol，在BSS段中存放的数据都是未被初始化的全局变量和静态变量，并默认会把这部分数据初始化为0.</p>
<hr>
<h2 id="堆"><a href="#堆" class="headerlink" title="堆"></a>堆</h2><p>堆是动态内存分配区，向高地址增长，堆中分配内存和释放内存需要调用malloc/new或free/delete。</p>
<hr>
<h2 id="栈"><a href="#栈" class="headerlink" title="栈"></a>栈</h2><p>栈和堆一般相邻，但沿着相反的方向增长。当栈指针和堆指针相等就说明栈内内存耗尽。栈中保存的是局部变量和每次函数调用时的信息。每次函数调用返回地址，一些调用者环境信息（比如寄存器）都被存放在栈中。然后新调用的函数就会在栈中为它们的自动或者临时变量分配内存空间，这就是C中递归函数调用的过程。每次递归函数调用自己，新的堆栈就会被创建，这样新的变量集合就不会被其他函数实例的变量集合影响了。</p>
<hr>
<h2 id="实例"><a href="#实例" class="headerlink" title="实例"></a>实例</h2><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="keyword">char</span> ro[] = &#123;<span class="string">"only read data area"</span>&#125;; <span class="comment">// 初始化只读存储区</span></span><br><span class="line"><span class="keyword">static</span> <span class="keyword">char</span> rw = &#123;<span class="string">"read write data area"</span>&#125;; <span class="comment">// 初始化读写数据段</span></span><br><span class="line"><span class="keyword">char</span> bss[<span class="number">100</span>];                             <span class="comment">// BSS段</span></span><br><span class="line"><span class="keyword">const</span> <span class="keyword">char</span> *pstrconst = <span class="string">"constant data"</span>;   <span class="comment">// 初始化只读存储区</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">(<span class="keyword">int</span> argc, <span class="keyword">char</span> argv[])</span></span></span><br><span class="line"><span class="function"></span>&#123;                                          <span class="comment">// 命令行参数防止在栈地址上的命令行参数空间中</span></span><br><span class="line">    <span class="keyword">int</span> a;                                 <span class="comment">// 栈上</span></span><br><span class="line">    <span class="keyword">char</span> a[<span class="number">100</span>];                           <span class="comment">// 栈</span></span><br><span class="line">    <span class="keyword">char</span> *c = <span class="string">"abcdef"</span>;                    <span class="comment">// c在栈上，"abcdef"在只读存储区，占7个字节</span></span><br><span class="line">    <span class="keyword">char</span> *p;                               <span class="comment">// 栈</span></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">int</span> rw2 = <span class="number">0</span>;                    <span class="comment">// 初始化读写数据段</span></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">char</span> bss2[<span class="number">100</span>];                 <span class="comment">// BSS段</span></span><br><span class="line">    p = (<span class="keyword">char</span> *)<span class="built_in">malloc</span>(<span class="number">10</span> * <span class="keyword">sizeof</span>(<span class="keyword">char</span>)); <span class="comment">// 在堆上分配10个字节</span></span><br><span class="line">    <span class="built_in">free</span>(p);</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<hr>
<h1 id="C-程序内存布局"><a href="#C-程序内存布局" class="headerlink" title="C++程序内存布局"></a>C++程序内存布局</h1><p>有关C++的内存布局，网上基本上都是按照C程序的内存布局来讲解，这其实是错误的，C程序和C++程序的内存布局是不一样的，在C++中内存可以分为以下5个部分：</p>
<p>​    · 代码段：这部分与C程序是大致相同的；</p>
<p>​    · 常量存储区：这部分存储的内容与C语言中初始化数据段中的只读数据段是一样的，用来存储C++常量；</p>
<p>​    · 全局/静态存储区：在C++中，不再区分数据段和BSS段，未初始化和初始化的全局/静态变量都会存储在这里，并且初始化为0；</p>
<p>​    · 堆：堆又分为new分配的存储区和malloc分配的内存块，new分配的存储区在程序结束之后，系统会帮助我们清理；</p>
<p>​    · 栈：栈和C程序的栈相同。</p>
<p>C和C++的内存布局大致上是相同的，主要区别在于C++引进了对象，C++对象中的成员函数存储在代码段中，数据成员才会存储在栈中，同样静态变量会存储在在全局/静态存储区，并且必须初始化。当然C++对象内存布局会涉及到继承，多态而出现多种变化，以及内存对齐的影响，对于这部分的内容参考：</p>
<p><a href="/2019/07/07/cpluscplusmemorypack/">内存对齐策略</a></p>
<p>C++之继承</p>
<p>C++之多态</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/07/07/cpluscplusmemorypack/" rel="next" title="C/C++内存对齐策略">
                <i class="fa fa-chevron-left"></i> C/C++内存对齐策略
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/07/07/cpluscplusorientedbase/" rel="prev" title="C++之面向对象基础">
                C++之面向对象基础 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            Overview
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">LuQiLin</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives">
              
                  <span class="site-state-item-count">80</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                
                  <span class="site-state-item-count">1</span>
                  <span class="site-state-item-name">categories</span>
                
              </div>
            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#C程序内存布局"><span class="nav-number">1.</span> <span class="nav-text">C程序内存布局</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#代码段"><span class="nav-number">1.1.</span> <span class="nav-text">代码段</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#初始化数据段"><span class="nav-number">1.2.</span> <span class="nav-text">初始化数据段</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#未初始化数据段（BSS段）"><span class="nav-number">1.3.</span> <span class="nav-text">未初始化数据段（BSS段）</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#堆"><span class="nav-number">1.4.</span> <span class="nav-text">堆</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#栈"><span class="nav-number">1.5.</span> <span class="nav-text">栈</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#实例"><span class="nav-number">1.6.</span> <span class="nav-text">实例</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#C-程序内存布局"><span class="nav-number">2.</span> <span class="nav-text">C++程序内存布局</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">LuQiLin</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Mist</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
